package com.aiden.app.common.http.interceptor

import android.content.Context
import com.aiden.app.common.extension.isNetWork
import okhttp3.CacheControl
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response


class HttpCacheInterceptor(private val maxAge: Int, private val context: Context) : Interceptor {
    override fun intercept(chain: Interceptor.Chain?): Response {
        val oldRequest: Request = chain!!.request()

        if (context.isNetWork()) {
            val response: Response = chain.proceed(oldRequest)
            return response.newBuilder()
                    .removeHeader("Pragma")
                    .removeHeader("Cache-Control")
                    .header("Cache-Control", "public, only-if-cached, max-age=$maxAge")
                    .build()

        } else {
            val newRequest = oldRequest.newBuilder()
                    .cacheControl(CacheControl.FORCE_CACHE)
                    .build()
            return chain.proceed(newRequest)
        }
    }
}